package com.hltx.controller.pay;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hltx.constants.CommonConstant;
import com.hltx.controller.base.BaseController;
import com.hltx.resolver.DefiniteException;
import com.hltx.util.CookieUtil;
import com.hltx.util.CustomUtil;
import com.hltx.util.HttpClientManagerT;

import net.sf.json.JSONObject;





/**
 * 微信controller
 * 
 * @author shibeilei
 *
 */
@Controller
public class WeixinController extends BaseController{

	protected Logger logger = LoggerFactory.getLogger(WeixinController.class);
	
	@Value("${wx.appid}")
	private String appid;
	
	@Value("${domain}")
	private String domain;
	
	@Value("${wx.appsecret}")
	private String appsecret;

	/**
	 * 获取微信公众号CODE
	 * 
	 * @return
	 */
	@RequestMapping(value = "/wxValidate/getWxJsApiCode", method = { RequestMethod.GET })
	public void getWxJsApiCode(String goUrl,HttpServletRequest request, HttpServletResponse response) {
		StringBuffer url = new StringBuffer();
		String contextPath = request.getContextPath();
		url.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=").append(appid);
		url.append("&redirect_uri=").append(domain).append(contextPath).append("/wxValidate/getWxJsApiOpenid?goUrl=").append(goUrl);
		url.append("&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
		
		CustomUtil.doBgReq(response, "<script> window.location.href = '" + url.toString()
				+ "';</script>");
		
	}
	
	/**
	 * 获取微信公众号openid
	 * 
	 * @return
	 */
	@RequestMapping(value = "/wxValidate/getWxJsApiOpenid", method = { RequestMethod.GET })
	public String getWxJsApiOpenid(String goUrl, String code,
			HttpSession session, HttpServletResponse response) {
		if (!StringUtils.isEmpty(code)) {
			StringBuffer url = new StringBuffer();
			url.append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=").append(appid);
			url.append("&secret=").append(appsecret).append("&code=").append(code).append("&grant_type=authorization_code");
			
			String res = HttpClientManagerT.getData(url.toString());
			try {
				JSONObject openjson = JSONObject.fromObject(res);
				String openid = openjson.getString("openid");
				session.setAttribute(CommonConstant.OPEN_KEY, openid);
				CookieUtil.setCookie(response, CommonConstant.OPEN_KEY, openid, 15);

			} catch (Exception e) {
				e.printStackTrace();
				throw new DefiniteException("微信授权失败！");
			}
		}
		return "redirect:" + goUrl;
	}
	
	
	
}
